<!-- @format -->

<script setup lang="ts">
import { computed, ref } from 'vue'

const props = defineProps({
  users: {
    type: Array<any>,
    default: () => [],
  },
  currentUser: {
    type: Object,
    default: () => {},
  },

  changeUser: {
    type: Function,
    default: () => {},
  },
  addUser: {
    type: Function,
    default: () => {},
  },
})

const emit = defineEmits(['change', 'add'])

const showAddUser = ref(false)
const userName = ref('')
const isAddUser = ref(false)

const userOptions = computed(() => {
  return props.users.map((user) => {
    return {
      label: user.name,
      value: user.key,
      item: user,
    }
  })
})

const title = computed(() => {
  return isAddUser ? '新增' : '编辑'
})

const addEnabled = computed(() => {
  return props.users.length < 3
})

const showUserPopup = (id) => {
  isAddUser.value = id === 'add'
  userName.value = isAddUser.value ? '' : props.currentUser.name
  showAddUser.value = true
}

const onChange = (value) => {
  emit('change', value?.selectedItem?.item)
}

const onAdd = () => {
  emit('add', {
    isAdd: isAddUser.value,
    userName: userName.value,
    callback: (value) => {
      showAddUser.value = value
    },
  })
}
</script>

<template>
  <view class="users-list">
    <wd-drop-menu>
      <wd-drop-menu-item
        :modelValue="currentUser?.key"
        :options="userOptions"
        @change="onChange"
      />
    </wd-drop-menu>
    <!-- 编辑 -->
    <the-icon-btn
      key="note"
      icon="note"
      bgColor="green"
      size="24rpx"
      paddingOuter="12rpx"
      @click="showUserPopup('edit')"
    />
    <!-- 新增 -->
    <the-icon-btn
      v-if="addEnabled"
      key="add"
      icon="add"
      bgColor="green"
      paddingOuter="12rpx"
      @click="showUserPopup('add')"
    />

    <!-- 新增用户弹窗 -->
    <wd-popup v-model="showAddUser" position="top">
      <view class="dialog-container">
        <wd-navbar placeholder safeAreaInsetTop :title="title" />
        <view class="label-title">名称：</view>
        <input
          v-model="userName"
          placeholder="请输入名称"
          class="label-input mb-10"
          type="text"
        />
        <the-icon-btn
          title="确认"
          icon="check-bold"
          bgColor="white"
          color="#333"
          @click="onAdd"
        />
      </view>
    </wd-popup>
  </view>
</template>

<style scoped>
.mb-10 {
  margin-bottom: 20rpx;
}

.users-list {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

/* 修改记录和使用弹窗容器 */
.dialog-container {
  padding: 40rpx;
  padding-top: 0;
  border-radius: 32rpx 32rpx 0 0;
  text-align: left;
  line-height: 1.5;
}

.label-title {
  font-size: 28rpx;
  color: #222;
  margin: 8rpx 0;
}

.label-input {
  border: 1px solid #ddd;
  padding: 16rpx;
}
</style>
